package org.example.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * 给你两个非空 的链表，表示两个非负的整数。它们每位数字都是按照逆序的方式存储的，并且每个节点只能存储一位数字。
 * <p>
 * 请你将两个数相加，并以相同形式返回一个表示和的链表。
 * <p>
 * 你可以假设除了数字 0 之外，这两个数都不会以 0开头。
 *
 * @author shenguangyang
 */
public class N001_AddTwoNumbers {
   public static class LinkedList {
        ListNode head;

        public LinkedList() {
            head = null;
        }

        public void addLast(ListNode node) {
            if (head == null) {
                head = node;
                return;
            }
            ListNode tempHead = head;
            while (tempHead.next != null) {
                tempHead = tempHead.next;
            }
            tempHead.next = node;
        }

        public static void printf(ListNode head) {
            if (head == null) {
                return;
            }
            List<Integer> data = new ArrayList<>();
            ListNode tempHead = head;
            while (tempHead != null) {
                data.add(tempHead.val);
                tempHead = tempHead.next;
            }
            System.out.println(data);
        }
    }
    /**
     * Definition for singly-linked list.
     */
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 链表头节点，输出的时候这个节点不要
        ListNode resNode = new ListNode(-1);
        ListNode curNode = resNode;
        // 进位
        int carry = 0;
        // 上数
        int l1Val;
        // 下数
        int l2Val;
        int temp;
        while (l1 != null || l2 != null || carry > 0) {
            l1Val = l1 == null ? 0 : l1.val;
            l2Val = l2 == null ? 0 : l2.val;
            temp = l1Val + l2Val + carry; //上数 加 下数 加 进位
            carry = temp / 10;
            curNode.next = new ListNode(temp % 10);
            curNode = curNode.next;

            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        
        return resNode.next;
    }

    public static void main(String[] args) {
        LinkedList l1 = new LinkedList();
        l1.addLast(new ListNode(2));
        l1.addLast(new ListNode(4));
        l1.addLast(new ListNode(9));

        LinkedList l2 = new LinkedList();
        l2.addLast(new ListNode(5));
        l2.addLast(new ListNode(6));
        l2.addLast(new ListNode(4));
        l2.addLast(new ListNode(9));

        ListNode listNode = addTwoNumbers(l1.head, l2.head);
        LinkedList.printf(listNode);
    }

}
